package sdk

import (
	"fmt"

	"gitee.com/linxing_3/youye-core/logger"
	"gitee.com/linxing_3/youye-core/sdk/application"
	"gitee.com/linxing_3/youye-core/sdk/config"
	"gitee.com/linxing_3/youye-core/sdk/pkg/jwtauth"
	"gitee.com/linxing_3/youye-core/storage"

	"github.com/gin-gonic/gin"
	"github.com/google/wire"
	"gorm.io/gorm"
)

var Provider = wire.NewSet(
	GetDefaultAppGorm,
	GetCacheAdapte,
	GetGinEngine,
	GetLogger,
	GetStorageSet,
	config.Provider,
)

func moduleUnregistErr(msg string) error {
	return fmt.Errorf("%s not regist to app", msg)
}

func GetStorageSet(app application.IApplication) (*application.StorageSet, error) {
	storageSet := app.GetStorage()
	if storageSet != nil {
		return storageSet, nil
	}
	return nil, moduleUnregistErr("storage set")
}

func GetDefaultAppGorm(app application.IApplication) (*gorm.DB, error) {
	db := app.GetDbByKey("*")
	if db == nil {
		return nil, moduleUnregistErr("gorm db")
	}

	return db, nil
}

func GetCacheAdapte(app application.IApplication) (storage.AdapterCache, error) {
	adapter := app.GetCacheAdapter()
	if adapter != nil {
		return adapter, nil
	}
	return nil, moduleUnregistErr("cache adapter")
}

func GetGinEngine(app application.IApplication) (*gin.Engine, error) {
	httpHandler := app.GetEngine()
	switch h := httpHandler.(type) {
	case *gin.Engine:
		return h, nil
	default:
		return nil, moduleUnregistErr("gin engine")
	}
}

func GetLogger(app application.IApplication) (logger.Logger, error) {
	return app.GetLogger(), nil
}

func GetAuth(app application.IApplication) (jwtauth.IAuth, error) {
	auth := app.GetAuth()
	if auth != nil {
		return auth, nil
	}
	return nil, moduleUnregistErr("auth")
}
